<template>
  <div class="login-container">
    <!-- 3D背景画布 -->
    <canvas ref="canvasRef" class="background-canvas"></canvas>
    
    <!-- 登录表单 -->
    <div class="login-form-container">
      <div class="login-form-wrapper">
        <!-- 系统标题 -->
        <div class="system-title">
          <h1 class="title-main">电商用户行为分析系统</h1>
          <p class="title-sub"></p>
        </div>
        
        <!-- 登录表单 -->
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          @submit.prevent="handleLogin"
        >
          <div class="form-title">
            <h2>管理员登录</h2>
            <p>请输入管理员账号和密码</p>
          </div>
          
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入管理员账号"
              size="large"
              prefix-icon="User"
              clearable
              @keyup.enter="handleLogin"
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              prefix-icon="Lock"
              show-password
              clearable
              @keyup.enter="handleLogin"
            />
          </el-form-item>
          
          <el-form-item>
            <el-checkbox v-model="loginForm.remember" class="remember-me">
              记住我
            </el-checkbox>
          </el-form-item>
          
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="login-button"
              :loading="loading"
              @click="handleLogin"
            >
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>
        
        <!-- 底部信息 -->
        <div class="login-footer">
          <p>© 2025 电商用户行为分析系统</p>
          <p class="system-info">仅供授权管理员使用</p>
        </div>
      </div>
    </div>
    
    <!-- 装饰元素 -->
    <div class="decoration-elements">
      <div class="floating-cube cube-1"></div>
      <div class="floating-cube cube-2"></div>
      <div class="floating-cube cube-3"></div>
      <div class="floating-sphere sphere-1"></div>
      <div class="floating-sphere sphere-2"></div>
      <!-- 星星装饰 -->
      <div class="star star-1">✦</div>
      <div class="star star-2">✧</div>
      <div class="star star-3">✦</div>
      <div class="star star-4">✧</div>
      <div class="star star-5">✦</div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'
import * as THREE from 'three'

const router = useRouter()
const userStore = useUserStore()

// 表单引用
const loginFormRef = ref(null)
const canvasRef = ref(null)

// 加载状态
const loading = ref(false)

// 登录表单数据
const loginForm = reactive({
  username: 'admin',
  password: 'admin',
  remember: false
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入管理员账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入管理员密码', trigger: 'blur' },
    { min: 3, max: 50, message: '密码长度在 3 到 50 个字符', trigger: 'blur' }
  ]
}

// 3D场景相关变量
let scene, camera, renderer, particles, animationId

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) return
    
    loading.value = true
    
    // 模拟登录API调用
    const result = await userStore.login({
      username: loginForm.username,
      password: loginForm.password
    })
    
    if (result.success) {
      const user = result.data.user
      ElMessage.success(`欢迎回来，${user.display_name || user.username}！`)

      // 记住我功能
      if (loginForm.remember) {
        localStorage.setItem('rememberedUsername', loginForm.username)
      } else {
        localStorage.removeItem('rememberedUsername')
      }

      // 显示用户角色信息
      if (user.role_name) {
        setTimeout(() => {
          ElMessage.info(`当前身份：${user.role_name}${user.department ? ` - ${user.department}` : ''}`)
        }, 1000)
      }

      // 跳转到仪表板
      router.push('/dashboard')
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error('登录失败，请重试')
  } finally {
    loading.value = false
  }
}

// 初始化3D背景
const init3DBackground = () => {
  if (!canvasRef.value) {
    console.warn('Canvas element not found')
    return
  }

  try {
    // 创建场景
    scene = new THREE.Scene()

    // 创建相机
    camera = new THREE.PerspectiveCamera(
      75,
      window.innerWidth / window.innerHeight,
      0.1,
      1000
    )
    camera.position.z = 5

    // 创建渲染器
    renderer = new THREE.WebGLRenderer({
      canvas: canvasRef.value,
      alpha: true,
      antialias: true
    })
    renderer.setSize(window.innerWidth, window.innerHeight)
    renderer.setClearColor(0x000000, 0)

    // 创建粒子系统
    createParticles()

    // 添加光源
    const ambientLight = new THREE.AmbientLight(0x404040, 0.6)
    scene.add(ambientLight)

    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8)
    directionalLight.position.set(1, 1, 1)
    scene.add(directionalLight)

    // 开始动画
    animate()
  } catch (error) {
    console.error('3D背景初始化失败:', error)
  }
}

// 创建粒子系统
const createParticles = () => {
  const particleCount = 1000
  const positions = new Float32Array(particleCount * 3)
  const colors = new Float32Array(particleCount * 3)
  
  for (let i = 0; i < particleCount; i++) {
    // 位置
    positions[i * 3] = (Math.random() - 0.5) * 20
    positions[i * 3 + 1] = (Math.random() - 0.5) * 20
    positions[i * 3 + 2] = (Math.random() - 0.5) * 20
    
    // 颜色 (星空蓝色系渐变)
    const color = new THREE.Color()
    color.setHSL(0.55 + Math.random() * 0.15, 0.7, 0.5 + Math.random() * 0.3)
    colors[i * 3] = color.r
    colors[i * 3 + 1] = color.g
    colors[i * 3 + 2] = color.b
  }
  
  const geometry = new THREE.BufferGeometry()
  geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3))
  geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3))
  
  const material = new THREE.PointsMaterial({
    size: 0.05,
    vertexColors: true,
    transparent: true,
    opacity: 0.8
  })
  
  particles = new THREE.Points(geometry, material)
  scene.add(particles)
}

// 动画循环
const animate = () => {
  if (!renderer || !scene || !camera) return

  animationId = requestAnimationFrame(animate)

  try {
    // 旋转粒子系统
    if (particles) {
      particles.rotation.x += 0.001
      particles.rotation.y += 0.002
    }

    // 相机轻微摆动
    if (camera) {
      camera.position.x = Math.sin(Date.now() * 0.0005) * 0.5
      camera.position.y = Math.cos(Date.now() * 0.0003) * 0.3
    }

    renderer.render(scene, camera)
  } catch (error) {
    console.error('动画渲染错误:', error)
    if (animationId) {
      cancelAnimationFrame(animationId)
    }
  }
}

// 处理窗口大小变化
const handleResize = () => {
  if (!camera || !renderer) return
  
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
  renderer.setSize(window.innerWidth, window.innerHeight)
}

// 组件挂载
onMounted(() => {
  // 检查是否记住了用户名
  const rememberedUsername = localStorage.getItem('rememberedUsername')
  if (rememberedUsername) {
    loginForm.username = rememberedUsername
    loginForm.remember = true
  }

  // 初始化3D背景 - 增加延迟确保DOM完全渲染
  setTimeout(() => {
    if (canvasRef.value) {
      init3DBackground()
    }
  }, 300)

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

// 组件卸载
onUnmounted(() => {
  // 清理动画
  if (animationId) {
    cancelAnimationFrame(animationId)
    animationId = null
  }

  // 清理Three.js资源
  if (renderer) {
    renderer.dispose()
    renderer = null
  }

  if (scene) {
    scene.clear()
    scene = null
  }

  if (particles) {
    if (particles.geometry) particles.geometry.dispose()
    if (particles.material) particles.material.dispose()
    particles = null
  }

  camera = null

  // 移除事件监听器
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.login-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(135deg, #0c1445 0%, #1e3c72 50%, #2a5298 100%);
}

.background-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.login-form-container {
  position: relative;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  padding: 20px;
}

.login-form-wrapper {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 20px;
  padding: 40px;
  box-shadow:
    0 20px 40px rgba(0, 0, 0, 0.1),
    0 0 0 1px rgba(255, 255, 255, 0.2);
  width: 100%;
  max-width: 450px;
  animation: slideInUp 0.8s ease-out;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(50px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.system-title {
  text-align: center;
  margin-bottom: 30px;
}

.title-main {
  font-size: 28px;
  font-weight: 700;
  background: linear-gradient(135deg, #1e3c72, #2a5298);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin: 0 0 8px 0;
  letter-spacing: -0.5px;
}

.title-sub {
  font-size: 14px;
  color: #666;
  margin: 0;
  font-weight: 400;
  letter-spacing: 0.5px;
}

.form-title {
  text-align: center;
  margin-bottom: 30px;
}

.form-title h2 {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
}

.form-title p {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.login-form {
  width: 100%;
}

.login-form :deep(.el-form-item) {
  margin-bottom: 24px;
}

.login-form :deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
}

.login-form :deep(.el-input__wrapper:hover) {
  border-color: #2a5298;
  box-shadow: 0 4px 12px rgba(42, 82, 152, 0.15);
}

.login-form :deep(.el-input__wrapper.is-focus) {
  border-color: #2a5298;
  box-shadow: 0 4px 12px rgba(42, 82, 152, 0.2);
}

.remember-me {
  color: #666;
  font-size: 14px;
}

.remember-me :deep(.el-checkbox__label) {
  color: #666;
}

.login-button {
  width: 100%;
  height: 48px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(135deg, #1e3c72, #2a5298);
  border: none;
  box-shadow: 0 4px 15px rgba(30, 60, 114, 0.3);
  transition: all 0.3s ease;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(30, 60, 114, 0.4);
}

.login-button:active {
  transform: translateY(0);
}

.login-footer {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.login-footer p {
  font-size: 12px;
  color: #999;
  margin: 0 0 4px 0;
}

.login-footer .system-info {
  font-size: 11px;
  color: #666;
  font-style: italic;
}

/* 装饰元素 */
.decoration-elements {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
  pointer-events: none;
}

.floating-cube {
  position: absolute;
  width: 20px;
  height: 20px;
  background: linear-gradient(45deg, rgba(42, 82, 152, 0.2), rgba(30, 60, 114, 0.4));
  border: 1px solid rgba(42, 82, 152, 0.3);
  backdrop-filter: blur(10px);
  animation: float 6s ease-in-out infinite;
  box-shadow: 0 4px 8px rgba(30, 60, 114, 0.2);
}

.cube-1 {
  top: 20%;
  left: 10%;
  animation-delay: 0s;
}

.cube-2 {
  top: 60%;
  right: 15%;
  animation-delay: 2s;
}

.cube-3 {
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

.floating-sphere {
  position: absolute;
  width: 15px;
  height: 15px;
  border-radius: 50%;
  background: linear-gradient(45deg, rgba(42, 82, 152, 0.3), rgba(30, 60, 114, 0.5));
  backdrop-filter: blur(10px);
  animation: float 8s ease-in-out infinite;
  box-shadow: 0 4px 8px rgba(30, 60, 114, 0.3);
}

.sphere-1 {
  top: 30%;
  right: 20%;
  animation-delay: 1s;
}

.sphere-2 {
  bottom: 40%;
  right: 10%;
  animation-delay: 3s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

/* 星星装饰 */
.star {
  position: absolute;
  color: rgba(255, 255, 255, 0.8);
  font-size: 16px;
  animation: twinkle 3s ease-in-out infinite;
  pointer-events: none;
}

.star-1 {
  top: 15%;
  left: 15%;
  animation-delay: 0s;
}

.star-2 {
  top: 25%;
  right: 25%;
  animation-delay: 1s;
}

.star-3 {
  top: 70%;
  left: 25%;
  animation-delay: 2s;
}

.star-4 {
  bottom: 25%;
  right: 15%;
  animation-delay: 0.5s;
}

.star-5 {
  top: 45%;
  left: 8%;
  animation-delay: 1.5s;
}

@keyframes twinkle {
  0%, 100% {
    opacity: 0.3;
    transform: scale(1);
  }
  50% {
    opacity: 1;
    transform: scale(1.2);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-form-wrapper {
    margin: 20px;
    padding: 30px 25px;
    max-width: none;
  }

  .title-main {
    font-size: 24px;
  }

  .form-title h2 {
    font-size: 20px;
  }

  .floating-cube,
  .floating-sphere,
  .star {
    display: none;
  }
}

@media (max-width: 480px) {
  .login-form-wrapper {
    margin: 10px;
    padding: 25px 20px;
  }

  .title-main {
    font-size: 20px;
  }

  .title-sub {
    font-size: 12px;
  }
}
</style>
